var log=console.log
export var uid = null
var roomId = null
var url = null
export function setUrl(Url) {
    url = Url
}
export function setRoomId(Roomid) {
    roomId = Roomid
}
export function setUid(Uid) {
    uid = Uid
}

export class Client{
    private static _ins: Client;
    private socket: WebSocket
    // roomId = "999999"
    receiveHandler
    handOutCardsHandler
    playOutHandler
    gameOverHandler
    connect(task=null){
        this.socket = new WebSocket(url)
        this.socket.onmessage = e=>{
            var data = JSON.parse(e.data)
            log(data)
            switch(data.event){
                case 'handOutCards':    
                case 'grabCard':        this.handOutCardsHandler(data); break;
                case 'grabCardRes':        
                case 'playOut':         this.playOutHandler(data);      break;
                case 'gameOver':        this.gameOverHandler(data);         break;
            }
            this.receiveHandler(data)
        }
        this.socket.onopen = e=>{
            if(task) this.doTask(task)
        }
    }
    static get(){
        if(this._ins==null) this._ins=new Client()
        return this._ins
    }

    doTask(task, param=null){
        var data = {
            uid, roomId , param
        }
        this.socket.send(JSON.stringify({
            task, data
        }))
    }
    close(){
        this.socket.close()
    }
}

import Alert from './alert'
export function alert(text,parent:cc.Node){
    cc.resources.load('alert',cc.Prefab,(err,asset:cc.Prefab)=>{
        var ins=cc.instantiate(asset).getComponent(Alert)
        ins.init(text,parent)
    })
}




